import 'package:flutter/material.dart';
import 'package:flutter_member/utils/over_scroll_behavior.dart';
import 'package:flutter_member/widget/course_tutorial.dart';
import 'package:flutter_member/widget/radio/WeChecklist.dart';
import 'package:flutter_member/widget/radio/index.dart';
import 'package:flutter_member/widget/search_records.dart';
import 'package:flutter_member/widget/search_width.dart';
import 'package:flutter_member/widget/universal_card.dart';
import 'package:flutter_member/widget/universal_card_item.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';

///课程的主要入口文件
class IndexCourse extends StatefulWidget {
  @override
  _IndexCourseState createState() => _IndexCourseState();
}

class _IndexCourseState extends State<IndexCourse> {
  //課程滑動控制器
  var _controller = ScrollController();
  var controllerIndex;
  List<CourseClass> _list = [];
  List<dynamic> _listCourseClass = [];
  List<ArticleDate> _describeList = [];
  bool isDrawer = false;
  var _focusView = false;
  var deleteFocus = false;
  List<SearchResults> _searchResultsList = [];

  List<String> latelyList = ['雅思課程A班'];
  List<String> popularList = ['雅思課程A班', '身心語言程式學A班', '拼貼課程A班'];

//  頂部tab標籤文字
  List<String> tabs = ['全部', '珠心算', '暑假課程', '成人課程'];
  bool isSelect = false;
  String value;
  var _indexedStack = 0;
  final List<WeRadiolistItem> options = [
    WeRadiolistItem(
      label: '智能排序',
      value: '智能排序',
    ),
    WeRadiolistItem(
      label: '距離 （由近到遠）',
      value: '距離',
    ),
    WeRadiolistItem(
      label: '學費 （由低到高）',
      value: '學費低到高',
    ),
    WeRadiolistItem(
      label: '學費 （由高到低）',
      value: '學費高到低',
    ),
    WeRadiolistItem(
      label: '上課日期 （由較早開課到較遲開課）',
      value: '上課日期較早',
    ),
  ];
  FocusNode _focusNode = FocusNode();
  var _search;

  var _searchEditing = new TextEditingController();

  @override
  void initState() {
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        setState(() {
          _focusView = true;
        });
      } else {
        setState(() {
          _focusView = false;
          //焦點被取消時進行搜索
          if (!deleteFocus) {
            _searchResultsList.clear();
            _searchCourse();
          }
        });
      }
    });
    _getCurriculum();
    _getCurriculums();

    //_getBranchLayer();
    _courseScroll();
    super.initState();
  }

  //搜索課程
  Future<void> _searchCourse() async {
//    includ cours
    QueryBuilder<ParseObject> query =
        QueryBuilder<ParseObject>(ParseObject('CourseClass'))
          ..whereEqualTo('title', _search)
          ..includeObject(['course.branch']);
    var res = await query.query();
    if (res.results != null) {
      res.results
          .map((v) => setState(() {
                //添加搜索紀錄
                if (_search != null) {
                  latelyList.add(_search);
                }
                _searchResultsList.clear();
                _searchResultsList.add(SearchResults(
                  v['objectId'],
                  v['course']['cover'] != null
                      ? v['course']['cover']['url']
                      : null,
                  v['title'],
                  v['startDate'],
                  v['endDate'],
                  v['course']['branch']['address'],
                  v['capacity'] - v['enrolled'],
                ));
                //跳轉搜索到紀錄模塊
                _indexedStack = 1;
                //關閉搜索紀錄
                _focusView = false;
                //關閉軟鍵盤
                _focusNode.unfocus();
                //初始化刪除紀錄按鈕狀態
                deleteFocus = false;
              }))
          .toList();
    } else {
      setState(() {
        //跳轉搜索到紀錄模塊
        _indexedStack = 1;
        //關閉搜索紀錄
        _focusView = false;
        //關閉軟鍵盤
        _focusNode.unfocus();
        //初始化刪除紀錄按鈕狀態
        deleteFocus = false;
      });
    }
  }

  //刪除搜索紀錄
  void _deleteSearch() {
    showModalBottomSheet(
        backgroundColor: Colors.transparent,
        context: context,
        builder: (BuildContext context) {
          return Container(
            padding: EdgeInsets.all(10),
            height: 200,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                    width: MediaQuery.of(context).size.width - 20,
                    height: 50,
                    decoration: BoxDecoration(
                      color: Color(0Xffececec),
                      borderRadius: BorderRadius.circular(15.0), //邊框
                    ),
                    child: Center(
                      child: Text(
                        '是否要清空搜索紀錄?',
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          color: Colors.black,
                          fontWeight: FontWeight.bold,
                          fontSize: 20,
                        ),
                      ),
                    )),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      latelyList.clear();
                      Navigator.of(context).pop();
                      //_focusView = false;
                    });
                  },
                  child: Container(
                      margin: EdgeInsets.only(top: 10),
                      width: MediaQuery.of(context).size.width - 20,
                      height: 50,
                      decoration: BoxDecoration(
                        color: Color(0Xffececec),
                        borderRadius: BorderRadius.circular(15.0), //邊框
                      ),
                      child: Center(
                        child: Text(
                          '確 認',
                          style: TextStyle(
                            color: Color(0Xff4d80c5),
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                          ),
                        ),
                      )),
                ),
                GestureDetector(
                  onTap: () => Navigator.of(context).pop(),
                  child: Container(
                      margin: EdgeInsets.only(top: 10),
                      width: MediaQuery.of(context).size.width - 20,
                      height: 50,
                      decoration: BoxDecoration(
                        color: Color(0Xffececec),
                        borderRadius: BorderRadius.circular(15.0), //邊框
                      ),
                      child: Center(
                        child: Text(
                          '取 消',
                          style: TextStyle(
                            color: Colors.red,
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                          ),
                        ),
                      )),
                )
              ],
            ),
          );
        });
  }

  Future<void> sortList(String v) {
    setState(() {
      if (v == "智能排序") {
        _list.sort((a, b) => (a.startDate).compareTo(b.startDate));
        _list.sort((a, b) => (b.fee).compareTo(a.fee));
      } else if (v == "距離") {
        print('暫無距離');
      } else if (v == "學費低到高") {
        _list.sort((a, b) => (a.fee).compareTo(b.fee));
      } else if (v == "學費高到低") {
        _list.sort((a, b) => (b.fee).compareTo(a.fee));
      } else if (v == "上課日期較早") {
        _list.sort((a, b) => (a.startDate).compareTo(b.startDate));
      }
    });
  }

//  获取课程信息
  Future<void> _getCurriculums() async {
    var queryCourse = QueryBuilder(ParseObject('CourseClass'))
      ..includeObject(['course']);
    var rep = await queryCourse.query();
    if (rep.success && rep.results != null) {
      rep.results.map((e) {
        return _listCourseClass.add({
          'objectId': e['objectId'],
          'title': e['title'],
          'src': e['course']['cover']['url'],
          'courseCategory': 'courseCategory',
          'blView': false
        });
      }).toList();
    }
  }

  Future<void> _getCurriculum() async {
    var response = await ParseObject('CourseClass').getAll();
    if (response.success) {
      for (var object in response.results) {
        Course course;
        var res =
            await ParseObject('Course').getObject(object['course']['objectId']);
        if (res.success) {
          var courseCategory;
          var res1 = await ParseObject('CourseCategory')
              .getObject(res.result['categories'][0]['objectId']);
          if (res1.success) {
            courseCategory = res1.result['title'];
          }
          course = Course(
              res.result['objectId'],
              res.result['title'],
              res.result['contents'],
              res.result['description'],
              res.result['cover']['url'],
              courseCategory);
        }
        _list.add(CourseClass(
            object['objectId'],
            object['title'],
            object['teacher']['objectId'],
            course,
            false,
            object['fee'],
            object['startDate']));
      }
      setState(() {
        //默認選中第一個
        _list[0].blView = true;
      });
    }
  }

  //新聞子組件
  Widget _buildRowNew() {
    return Container(
      height: ScreenUtil().setHeight(165),
      width: ScreenUtil().setWidth(340),
      child: Swiper(
        itemBuilder: _swiperBuilder,
        itemCount: 3,
        pagination: SwiperPagination(
            builder: DotSwiperPaginationBuilder(
          color: Colors.black54,
          activeColor: Colors.white,
        )),
        scrollDirection: Axis.horizontal,
        autoplay: true,
        onTap: (index) => print('点击了第$index个'),
      ),
    );
  }

  //輪播圖片
  Widget _swiperBuilder(BuildContext context, int index) {
    return (ClipRRect(
      borderRadius: BorderRadius.circular(20),
      child: Image.asset(
        'images/Rectangle.png',
        fit: BoxFit.fill,
      ),
    ));
  }

  //下拉刷新
  Future<Null> _refresh() async {
    print('下拉');
    setState(() {
      _describeList.clear();
      _list.clear();
    });
    _getCurriculum();
    _getCurriculums();

    return;
  }

  //監聽課程滑動
  _courseScroll() {
    _controller.addListener(() {
      setState(() {
        //計算出滑動的當前下標 寬度為150
        print('_controller.offset:${(_controller.offset)}');
        controllerIndex = (_controller.offset / 150).round();
        //如果拉到的最後
        if (_controller.position.pixels ==
            _controller.position.maxScrollExtent) {
          for (var c in _list) {
            c.blView = false;
          }
          _list[_list.length - 1].blView = true;
        } else {
          for (int i = 0; i < _list.length; i++) {
            if (i == controllerIndex) {
              _list[controllerIndex].blView = true;
            } else {
              _list[i].blView = false;
            }
          }
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    TabController _tabController;
    return DefaultTabController(
      length: tabs.length,
      child: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
            setState(() {
              isDrawer = false;
            });
          },
          child: Scaffold(
            body: GestureDetector(
                onTap: () {
                  //點擊任何位置關閉軟鍵盤
                  _focusNode.unfocus();
                },
                child: Container(
                  child: Column(
                    children: <Widget>[
                      _searchInput(),
                      Expanded(
                        child: Stack(
                          children: <Widget>[
                            IndexedStack(
                              index: _indexedStack,
                              alignment: Alignment.center,
                              children: <Widget>[
                                Container(
                                  child: Column(
                                    children: <Widget>[
                                      Container(
                                          child: Row(
                                        children: <Widget>[
                                          new IconButton(
                                            icon: Icon(
                                              Icons.reorder,
                                              color: Color(0xff707070),
                                            ),
                                            onPressed: () {
                                              showPub(context, width);
                                            },
                                          ),
                                          new Expanded(
                                            child: TabBar(
                                              indicatorColor: Colors.yellow,
                                              //指示器颜色
                                              isScrollable: true,
                                              indicatorWeight: 4,
                                              //指示器高度
                                              indicatorPadding:
                                                  EdgeInsets.fromLTRB(
                                                      35, 0, 35, 0),
                                              //底部指示器的Padding
                                              labelColor: Color(0xff2D7FC7),
                                              //选中label颜色
                                              unselectedLabelColor:
                                                  Color(0xffd9d9d9),
                                              //未选中label颜色
                                              labelStyle: TextStyle(
                                                  fontWeight: FontWeight.w500,
                                                  fontSize:
                                                      ScreenUtil().setSp(16)),
                                              tabs: tabs
                                                  .map((e) => Tab(
                                                        child: Text(e),
                                                      ))
                                                  .toList(),
                                              controller: _tabController,
                                            ),
                                          )
                                        ],
                                      )),
                                      Expanded(
                                        child: TabBarView(
                                          children: <Widget>[
                                            tabview(width),
                                            tabview(width),
                                            tabview(width),
                                            tabview(width),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                _searchResultsList.length != 0
                                    //有搜索結果
                                    ? _searchDataWidget()
                                    //無搜索結果
                                    : noDataWidget()
                              ],
                            ),
                            _focusView ? _searchRecords() : Container(),
                          ],
                        ),
                      )
                      //searchBar(width, height),
                    ],
                  ),
                )),
          )),
    );
  }

//  搜索成功
  Widget _searchDataWidget() {
    return Container(
//      padding: EdgeInsets.all(10),
      child: ScrollConfiguration(
        behavior: OverScrollBehavior(),
        child: ListView.separated(
            itemBuilder: (BuildContext context, int index) => UniversalCard(
                  title: _searchResultsList[index].title,
                  url: _searchResultsList[index].src,
                  children: [
                    UniversalCardItem(
                      icon: 'images/location.png',
                      title: _searchResultsList[index] != null
                          ? '${_searchResultsList[index].startDate.month}月${_searchResultsList[index].startDate.day}日' +
                              '-${_searchResultsList[index].endDate.month}月${_searchResultsList[index].endDate.day}日（逢星期六 17：30 - 19：30）'
                          : '暫無數據',
                    ),
                    UniversalCardItem(
                      icon: 'images/locations.png',
                      title: _searchResultsList[index] != null
                          ? _searchResultsList[index].address
                          : '暫無數據',
                    ),
                    myContainer(
                      MediaQuery.of(context).size.width,
                      _searchResultsList[index] != null
                          ? '名額剩餘：${_searchResultsList[index].surplusQuota}'
                          : '暫無數據',
                    ),
                    Container(
                      padding: EdgeInsets.all(5),
                      margin: EdgeInsets.only(left: 100),
                      alignment: Alignment.bottomRight,
                      decoration: BoxDecoration(
                          border:
                              Border.all(color: Color(0xff93BB24), width: 1.5),
                          borderRadius: BorderRadius.all(Radius.circular(50))),
                      child: Text(
                        '距離 ＜125m',
                        style: TextStyle(
                            color: Color(0xff93BB24),
                            fontSize: ScreenUtil().setSp(12),
                            fontWeight: FontWeight.w500),
                      ),
                    )
                  ],
                  onPressed: () {
                    Navigator.pushNamed(context, '/curriculumDetails',
                        arguments: {
                          'objectId': _searchResultsList[index].objectId
                        });
                  },
                ),
            separatorBuilder: (BuildContext context, int index) => Divider(),
            itemCount: _searchResultsList.length),
      ),
    );
  }

//  搜索输入框
  Widget _searchInput() {
    return SearchWidth(
      src: 'images/top_course.png',
      inputController: _searchEditing,
      focusNode: _focusNode,
      hintText: '搜尋課程',
      downColor: Color(0Xffffe7a7),
      upColor: Color(0Xffffc128),
      onChange: (v) {
        setState(() {
          _search = v;
        });
      },
      onPressed: () => setState(() {
        _searchResultsList.clear();
        _searchCourse();
      }),
    );
  }

// 搜索记录子组件
  Widget _searchRecords() {
    return SearchRecords(
      searchRecords: latelyList,
      searchHot: popularList,
      clear: () {
        deleteFocus = true;
        _deleteSearch();
      },
      onClick: (str) {
        //將搜索紀錄改成關鍵字
        _search = str;
        //將搜索紀錄輸入到輸入框
        _searchEditing.text = str;
        _searchResultsList.clear();
        _searchCourse();
      },
    );
  }

//  没有搜索到记录
  Widget noDataWidget() {
    return Container(
      child: Container(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Image.asset(
            'images/no_result1.png',
          ),
          Container(
            margin: EdgeInsets.only(top: 25),
            child: Image.asset(
              'images/no_result2.png',
            ),
          )
        ],
      )),
    );
  }

  Widget tabview(width) {
    return RefreshIndicator(
      onRefresh: _refresh,
      child: ScrollConfiguration(
          behavior: OverScrollBehavior(),
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                CourseTutorial(
                  listTuitionService: _listCourseClass,
                  mainColor: Color(0xff2D7FC7),
                  mainTitle: '最新課程',
                  mainTitleSize: 20,
                  path: '/curriculum/details',
                  isId: true,
                ),
                Container(
                  padding: EdgeInsets.only(left: 10, right: 10),
                  child: advertisement(_buildRowNew()),
                ),
                CourseTutorial(
                  listTuitionService: _listCourseClass,
                  mainColor: Color(0xff2D7FC7),
                  mainTitle: '推薦課程',
                  mainTitleSize: 20,
                  path: '/curriculum/details',
                  isId: true,
                ),
              ],
            ),
          )),
    );
  }

//分校信息文本框
  Widget myContainer(double width, String param) {
    return Container(
      width: width * 0.6 - 50 - 18,
      child: Text(
        param,
        //最大行數
        maxLines: 2,
        //overflow: TextOverflow.ellipsis,
        style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: ScreenUtil().setSp(12),
            color: Color(0xffFF0000)),
      ),
    );
  }

//region 底部彈窗
  void showPub(context, width) {
    showModalBottomSheet(
        context: context,
        backgroundColor: Colors.transparent,
        builder: (BuildContext context) {
          return _shareWidget(context, width);
        });
  }

//廣告
  Widget advertisement(Widget listViewDate) {
    return Container(
      height: ScreenUtil().setHeight(165),
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(8)),
      child: ScrollConfiguration(
          behavior: OverScrollBehavior(), child: listViewDate),
    );
  }

//  排序框
  Widget _shareWidget(context, width) {
    return Container(
      padding: EdgeInsets.all(5),
      child: Container(
        width: width,
        height: 500,
        decoration: BoxDecoration(
            color: Color(0xffc8daee),
            borderRadius: BorderRadius.all(Radius.circular(20))),
        child: Container(
            padding: EdgeInsets.only(
              top: 10,
            ),
            width: width,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(20))),
            child: Container(
              child: Column(
                children: <Widget>[
                  Center(
                    child: Container(
                      width: width * 0.15,
                      height: 5,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(20)),
                        color: Color(0xffaeaebe),
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(top: 30, bottom: 5),
                    child: Row(
                      children: <Widget>[
                        new Expanded(
                          child: InkWell(
                            child: Text('重設',
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  fontWeight: FontWeight.w800,
                                  fontSize: ScreenUtil().setSp(18),
                                  color: Color(0xff93BB24),
                                  fontFamily: "SemiBold",
                                )),
                            onTap: () {
                              print('重設');
                            },
                          ),
                          flex: 1,
                        ),
                        new Expanded(
                          child: Text('篩選',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontWeight: FontWeight.w800,
                                fontSize: ScreenUtil().setSp(18),
                                color: Color(0xff154D7C),
                                fontFamily: "SemiBold",
                              )),
                          flex: 1,
                        ),
                        new Expanded(
                          child: InkWell(
                            child: Text(
                              '完成',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                fontWeight: FontWeight.w800,
                                fontSize: ScreenUtil().setSp(18),
                                color: Color(0xff2D7FC7),
                                fontFamily: "SemiBold",
                              ),
                            ),
                            onTap: () {
                              print('完成');
                              sortList(value);
                              Navigator.pop(context);
                            },
                          ),
                          flex: 1,
                        ),
                      ],
                    ),
                  ),
                  Container(
                    color: Color(0xffeaebed),
                    width: width,
                    height: 1,
                  ),
                  Expanded(
                    child: ListView(
                      children: <Widget>[
                        Container(
                            child: Column(children: <Widget>[
                          WeRadiolist(
                            children: options,
                            onChange: (v) {
                              setState(() {
                                value = v;
                              });
                              print(v);
                            },
                          ),
                        ])),
                        Container(
                          padding:
                              EdgeInsets.only(left: 20, bottom: 15, top: 15),
                          child: Text(
                            '持續進修課程',
                            style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w500,
                                color: Color(0xffc7c9c0)),
                          ),
                        ),
                        WeChecklist(
                          align: 'right',
                          onChange: (v) {
                            print(v);
                          },
                          children: [
                            WeChecklistItem(
                              label: '使用持續進修',
                              value: '使用持續進修',
                            )
                          ],
                        )
                      ],
                    ),
                  ),
                ],
              ),
            )),
      ),
    );
  }

//endregion
}

class Course {
  final String objectId;
  final String title; //課程分類
  final String contents;
  final String description;
  final String src;
  final String courseCategory; //課程類別 持教
  Course(this.objectId, this.title, this.contents, this.description, this.src,
      this.courseCategory);
}

class ArticleDate {
  final String objectId;
  final String title;
  final DateTime updateAt;
  final String thePublisher;
  final String content;

  ArticleDate(this.objectId, this.title, this.thePublisher, this.content,
      this.updateAt);
}

class CourseClass {
  final String objectId;
  final String title; //班級名
  final String teacher; //老師
  final Course course;
  bool blView;
  final num fee;
  final DateTime startDate;

  CourseClass(this.objectId, this.title, this.teacher, this.course, this.blView,
      this.fee, this.startDate);
}

class SearchResults {
  final String objectId;
  final String src;
  final String title;
  final DateTime startDate;
  final DateTime endDate;
  final String address;
  final int surplusQuota;

  SearchResults(this.objectId, this.src, this.title, this.startDate,
      this.endDate, this.address, this.surplusQuota);
}
